<?php

defined('SYSPATH') or die('Access error!');

/**
 * utf8 helper 类
 */
class UTF8
{

    /**
     * 服务器是否支持UTF-8？
     */
    public static $server_utf8 = NULL;
    public static $called = array();

    /**
     *  递归地清除数组，对象和字符串 
     *     UTF8::clean($_GET);
     * @param   mixed  
     * @param   string  
     * @return  mixed
     */
    public static function clean($var, $charset = NULL)
    {
        if (!$charset)
        {
            $charset = Core::$charset;
        }

        if (is_array($var) OR is_object($var))
        {
            foreach ($var as $key => $val)
            {
                $var[self::clean($key)] = self::clean($val);
            }
        }
        elseif (is_string($var) AND $var !== '')
        {
            $var = self::strip_ascii_ctrl($var);

            if (!self::is_ascii($var))
            {
                $error_reporting = error_reporting(~E_NOTICE);

                $var = iconv($charset, $charset . '//IGNORE', $var);

                error_reporting($error_reporting);
            }
        }

        return $var;
    }

    /**
     * 测试一个字符串是否只包含7位ASCII字节。这是用来确定何时使用本机的功能或UTF-8的功能。
     *
     *     $ascii = UTF8::is_ascii($str);
     *
     * @param   mixed    string or array of strings to check
     * @return  boolean
     */
    public static function is_ascii($str)
    {
        if (is_array($str))
        {
            $str = implode($str);
        }

        return !preg_match('/[^\x00-\x7F]/S', $str);
    }

    /**
     * 去掉了设备的控制代码在ASCII范围内。
     *
     *     $str = UTF8::strip_ascii_ctrl($str);
     *
     * @param   string 
     * @return  string
     */
    public static function strip_ascii_ctrl($str)
    {
        return preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S', '', $str);
    }

    /**
     * 去掉了所有非7位ASCII.
     *
     *     $str = UTF8::strip_non_ascii($str);
     *
     * @param   string 
     * @return  string
     */
    public static function strip_non_ascii($str)
    {
        return preg_replace('/[^\x00-\x7F]+/S', '', $str);
    }

    /**
     *     $ascii = UTF8::transliterate_to_ascii($utf8);
     *
     * @param   string   string to transliterate
     * @param   integer  -1 lowercase only, +1 uppercase only, 0 both cases
     * @return  string
     */
    public static function transliterate_to_ascii($str, $case = 0)
    {
        if (!isset(self::$called[__FUNCTION__]))
        {
            require SYSPATH . 'utf8' . DIRECTORY_SEPARATOR . __FUNCTION__ . EXT;

            self::$called[__FUNCTION__] = TRUE;
        }

        return _transliterate_to_ascii($str, $case);
    }

    /**
     * 返回给定的字符串的长度
     *
     *     $length = UTF8::strlen($str);
     *
     * @param   string  
     * @return  integer
     * @uses    UTF8::$server_utf8
     */
    public static function strlen($str)
    {
        if (UTF8::$server_utf8)
            return mb_strlen($str, Core::$charset);

        if (!isset(self::$called[__FUNCTION__]))
        {
            require SYSPATH . 'utf8' . DIRECTORY_SEPARATOR . __FUNCTION__ . EXT;
            self::$called[__FUNCTION__] = TRUE;
        }
        return _strlen($str);
    }

    /**
     *  $position = UTF8::strpos($str, $search);
     * 
     * @param type $str
     * @param type $search
     * @param type $offset
     * @return type 
     */
    public static function strpos($str, $search, $offset = 0)
    {
        if (UTF8::$server_utf8)
            return mb_strpos($str, $search, $offset, Core::$charset);

        if (!isset(self::$called[__FUNCTION__]))
        {
            require SYSPATH . 'utf8' . DIRECTORY_SEPARATOR . __FUNCTION__ . EXT;

            self::$called[__FUNCTION__] = TRUE;
        }

        return _strpos($str, $search, $offset);
    }

    /**
     *   $position = UTF8::strrpos($str, $search);
     * 
     * @param type $str
     * @param type $search
     * @param type $offset
     * @return type 
     */
    public static function strrpos($str, $search, $offset = 0)
    {
        if (UTF8::$server_utf8)
            return mb_strrpos($str, $search, $offset, Core::$charset);

        if (!isset(self::$called[__FUNCTION__]))
        {
            require SYSPATH . 'utf8' . DIRECTORY_SEPARATOR . __FUNCTION__ . EXT;
            self::$called[__FUNCTION__] = TRUE;
        }
        return _strrpos($str, $search, $offset);
    }

    /**
     *   截取字符串 $offset 为第几位置
     *     $sub = UTF8::substr($str, $offset);
     * @author  Chris Smith <chris@jalakai.co.uk>
     * @param   string   input string
     * @param   integer  offset
     * @param   integer  length limit
     * @return  string
     * @uses    UTF8::$server_utf8
     * @uses    Core::$charset
     */
    public static function substr($str, $offset, $length = NULL)
    {
        if (UTF8::$server_utf8)
            return ($length === NULL) ? mb_substr($str, $offset, mb_strlen($str), Core::$charset) : mb_substr($str, $offset, $length, Core::$charset);

        if (!isset(self::$called[__FUNCTION__]))
        {
            require SYSPATH . 'utf8' . DIRECTORY_SEPARATOR . __FUNCTION__ . EXT;
            self::$called[__FUNCTION__] = TRUE;
        }
        return _substr($str, $offset, $length);
    }

    /**
     *  //替换字符串
     *     $str = UTF8::substr_replace($str, $replacement, $offset);
     * @param type $str
     * @param type $replacement
     * @param type $offset
     * @param type $length
     * @return type 
     */
    public static function substr_replace($str, $replacement, $offset, $length = NULL)
    {
        if (!isset(self::$called[__FUNCTION__]))
        {
            require SYSPATH . 'utf8' . DIRECTORY_SEPARATOR . __FUNCTION__ . EXT;
            self::$called[__FUNCTION__] = TRUE;
        }
        return _substr_replace($str, $replacement, $offset, $length);
    }

    /**
     *   //转为小写
     *     $str = UTF8::strtolower($str);
     * @param type $str
     * @return type 
     */
    public static function strtolower($str)
    {
        if (UTF8::$server_utf8)
            return mb_strtolower($str, Core::$charset);

        if (!isset(self::$called[__FUNCTION__]))
        {
            require SYSPATH . 'utf8' . DIRECTORY_SEPARATOR . __FUNCTION__ . EXT;
            self::$called[__FUNCTION__] = TRUE;
        }

        return _strtolower($str);
    }

    /**
     * 转为大写
     * @param type $str
     * @return type 
     */
    public static function strtoupper($str)
    {
        if (UTF8::$server_utf8)
            return mb_strtoupper($str, Core::$charset);
        if (!isset(self::$called[__FUNCTION__]))
        {
            require SYSPATH . 'utf8' . DIRECTORY_SEPARATOR . __FUNCTION__ . EXT;
            self::$called[__FUNCTION__] = TRUE;
        }

        return _strtoupper($str);
    }

    /**
     *  首字母大写
     *     $str = UTF8::ucfirst($str);
     * @param type $str
     * @return type 
     */
    public static function ucfirst($str)
    {

        if (!isset(self::$called[__FUNCTION__]))
        {
            require SYSPATH . 'utf8' . DIRECTORY_SEPARATOR . __FUNCTION__ . EXT;
            self::$called[__FUNCTION__] = TRUE;
        }

        return _ucfirst($str);
    }

    /**
     * 例如输出 My Name Is Liuxudong(my name is liuxudong)
     *     $str = UTF8::ucwords($str);
     * @param type $str
     * @return type 
     */
    public static function ucwords($str)
    {
        if (!isset(self::$called[__FUNCTION__]))
        {
            require SYSPATH . 'utf8' . DIRECTORY_SEPARATOR . __FUNCTION__ . EXT;
            self::$called[__FUNCTION__] = TRUE;
        }

        return _ucwords($str);
    }

    /**
     * 比较2个字符串的长度
     *     $compare = UTF8::strcasecmp($str1, $str2);
     * @param type $str1
     * @param type $str2
     * @return type 
     */
    public static function strcasecmp($str1, $str2)
    {
        if (!isset(self::$called[__FUNCTION__]))
        {
            require SYSPATH . 'utf8' . DIRECTORY_SEPARATOR . __FUNCTION__ . EXT;
            self::$called[__FUNCTION__] = TRUE;
        }

        return _strcasecmp($str1, $str2);
    }

    /**
     * Returns a string or an array with all occurrences of search in subject
     * (ignoring case) and replaced with the given replace value. This is a
     * UTF8-aware version of [str_ireplace](http://php.net/str_ireplace).
     *
     * [!!] This function is very slow compared to the native version. Avoid
     * using it when possible.
     *
     * @author  Harry Fuecks <hfuecks@gmail.com
     * @param   string|array  text to replace
     * @param   string|array  replacement text
     * @param   string|array  subject text
     * @param   integer       number of matched and replaced needles will be returned via this parameter which is passed by reference
     * @return  string        if the input was a string
     * @return  array         if the input was an array
     */
    public static function str_ireplace($search, $replace, $str, & $count = NULL)
    {
        if (!isset(self::$called[__FUNCTION__]))
        {
            require SYSPATH . 'utf8' . DIRECTORY_SEPARATOR . __FUNCTION__ . EXT;

            self::$called[__FUNCTION__] = TRUE;
        }

        return _str_ireplace($search, $replace, $str, $count);
    }

    /**
     * 返回$search 中是否在$str中 如果存在就返回$serach
     *
     *     $found = UTF8::stristr($str, $search);
     * @param type $str
     * @param type $search
     * @return type 
     */
    public static function stristr($str, $search)
    {
        if (!isset(self::$called[__FUNCTION__]))
        {
            require SYSPATH . 'utf8' . DIRECTORY_SEPARATOR . __FUNCTION__ . EXT;

            self::$called[__FUNCTION__] = TRUE;
        }

        return _stristr($str, $search);
    }

    /**
     * Finds the length of the initial segment matching mask. This is a
     * UTF8-aware version of [strspn](http://php.net/strspn).
     *
     *     $found = UTF8::strspn($str, $mask);
     *
     * @author Harry Fuecks <hfuecks@gmail.com>
     * @param   string   input string
     * @param   string   mask for search
     * @param   integer  start position of the string to examine
     * @param   integer  length of the string to examine
     * @return  integer  length of the initial segment that contains characters in the mask
     */
    public static function strspn($str, $mask, $offset = NULL, $length = NULL)
    {
        if (!isset(self::$called[__FUNCTION__]))
        {
            require SYSPATH . 'utf8' . DIRECTORY_SEPARATOR . __FUNCTION__ . EXT;

            // Function has been called
            self::$called[__FUNCTION__] = TRUE;
        }

        return _strspn($str, $mask, $offset, $length);
    }

    /**
     * Finds the length of the initial segment not matching mask. This is a
     * UTF8-aware version of [strcspn](http://php.net/strcspn).
     *
     *     $found = UTF8::strcspn($str, $mask);
     *
     * @author  Harry Fuecks <hfuecks@gmail.com>
     * @param   string   input string
     * @param   string   mask for search
     * @param   integer  start position of the string to examine
     * @param   integer  length of the string to examine
     * @return  integer  length of the initial segment that contains characters not in the mask
     */
    public static function strcspn($str, $mask, $offset = NULL, $length = NULL)
    {
        if (!isset(self::$called[__FUNCTION__]))
        {
            require SYSPATH . 'utf8' . DIRECTORY_SEPARATOR . __FUNCTION__ . EXT;

            // Function has been called
            self::$called[__FUNCTION__] = TRUE;
        }

        return _strcspn($str, $mask, $offset, $length);
    }

    /**
     * Pads a UTF-8 string to a certain length with another string. This is a
     * UTF8-aware version of [str_pad](http://php.net/str_pad).
     *
     *     $str = UTF8::str_pad($str, $length);
     *
     * @author  Harry Fuecks <hfuecks@gmail.com>
     * @param   string   input string
     * @param   integer  desired string length after padding
     * @param   string   string to use as padding
     * @param   string   padding type: STR_PAD_RIGHT, STR_PAD_LEFT, or STR_PAD_BOTH
     * @return  string
     */
    public static function str_pad($str, $final_str_length, $pad_str = ' ', $pad_type = STR_PAD_RIGHT)
    {
        if (!isset(self::$called[__FUNCTION__]))
        {
            require SYSPATH . 'utf8' . DIRECTORY_SEPARATOR . __FUNCTION__ . EXT;

            // Function has been called
            self::$called[__FUNCTION__] = TRUE;
        }

        return _str_pad($str, $final_str_length, $pad_str, $pad_type);
    }

    /**
     * Converts a UTF-8 string to an array. This is a UTF8-aware version of
     * [str_split](http://php.net/str_split).
     *
     *     $array = UTF8::str_split($str);
     *
     * @author  Harry Fuecks <hfuecks@gmail.com>
     * @param   string   input string
     * @param   integer  maximum length of each chunk
     * @return  array
     */
    public static function str_split($str, $split_length = 1)
    {
        if (!isset(self::$called[__FUNCTION__]))
        {
            require SYSPATH . 'utf8' . DIRECTORY_SEPARATOR . __FUNCTION__ . EXT;

            // Function has been called
            self::$called[__FUNCTION__] = TRUE;
        }

        return _str_split($str, $split_length);
    }

    /**
     * Reverses a UTF-8 string. This is a UTF8-aware version of [strrev](http://php.net/strrev).
     *
     *     $str = UTF8::strrev($str);
     *
     * @author  Harry Fuecks <hfuecks@gmail.com>
     * @param   string   string to be reversed
     * @return  string
     */
    public static function strrev($str)
    {
        if (!isset(self::$called[__FUNCTION__]))
        {
            require SYSPATH . 'utf8' . DIRECTORY_SEPARATOR . __FUNCTION__ . EXT;

            // Function has been called
            self::$called[__FUNCTION__] = TRUE;
        }

        return _strrev($str);
    }

    /**
     * Strips whitespace (or other UTF-8 characters) from the beginning and
     * end of a string. This is a UTF8-aware version of [trim](http://php.net/trim).
     *
     *     $str = UTF8::trim($str);
     *
     * @author  Andreas Gohr <andi@splitbrain.org>
     * @param   string   input string
     * @param   string   string of characters to remove
     * @return  string
     */
    public static function trim($str, $charlist = NULL)
    {
        if (!isset(self::$called[__FUNCTION__]))
        {
            require SYSPATH . 'utf8' . DIRECTORY_SEPARATOR . __FUNCTION__ . EXT;

            // Function has been called
            self::$called[__FUNCTION__] = TRUE;
        }

        return _trim($str, $charlist);
    }

    /**
     * Strips whitespace (or other UTF-8 characters) from the beginning of
     * a string. This is a UTF8-aware version of [ltrim](http://php.net/ltrim).
     *
     *     $str = UTF8::ltrim($str);
     *
     * @author  Andreas Gohr <andi@splitbrain.org>
     * @param   string   input string
     * @param   string   string of characters to remove
     * @return  string
     */
    public static function ltrim($str, $charlist = NULL)
    {
        if (!isset(self::$called[__FUNCTION__]))
        {
            require SYSPATH . 'utf8' . DIRECTORY_SEPARATOR . __FUNCTION__ . EXT;

            // Function has been called
            self::$called[__FUNCTION__] = TRUE;
        }

        return _ltrim($str, $charlist);
    }

    /**
     * Strips whitespace (or other UTF-8 characters) from the end of a string.
     * This is a UTF8-aware version of [rtrim](http://php.net/rtrim).
     *
     *     $str = UTF8::rtrim($str);
     *
     * @author  Andreas Gohr <andi@splitbrain.org>
     * @param   string   input string
     * @param   string   string of characters to remove
     * @return  string
     */
    public static function rtrim($str, $charlist = NULL)
    {
        if (!isset(self::$called[__FUNCTION__]))
        {
            require SYSPATH . 'utf8' . DIRECTORY_SEPARATOR . __FUNCTION__ . EXT;

            // Function has been called
            self::$called[__FUNCTION__] = TRUE;
        }

        return _rtrim($str, $charlist);
    }

    /**
     * Returns the unicode ordinal for a character. This is a UTF8-aware
     * version of [ord](http://php.net/ord).
     *
     *     $digit = UTF8::ord($character);
     *
     * @author  Harry Fuecks <hfuecks@gmail.com>
     * @param   string   UTF-8 encoded character
     * @return  integer
     */
    public static function ord($chr)
    {
        if (!isset(self::$called[__FUNCTION__]))
        {
            require SYSPATH . 'utf8' . DIRECTORY_SEPARATOR . __FUNCTION__ . EXT;

            // Function has been called
            self::$called[__FUNCTION__] = TRUE;
        }

        return _ord($chr);
    }

    /**
     * Takes an UTF-8 string and returns an array of ints representing the Unicode characters.
     * Astral planes are supported i.e. the ints in the output can be > 0xFFFF.
     * Occurrences of the BOM are ignored. Surrogates are not allowed.
     *
     *     $array = UTF8::to_unicode($str);
     *
     * The Original Code is Mozilla Communicator client code.
     * The Initial Developer of the Original Code is Netscape Communications Corporation.
     * Portions created by the Initial Developer are Copyright (C) 1998 the Initial Developer.
     * Ported to PHP by Henri Sivonen <hsivonen@iki.fi>, see <http://hsivonen.iki.fi/php-utf8/>
     * Slight modifications to fit with phputf8 library by Harry Fuecks <hfuecks@gmail.com>
     *
     * @param   string  UTF-8 encoded string
     * @return  array   unicode code points
     * @return  FALSE   if the string is invalid
     */
    public static function to_unicode($str)
    {
        if (!isset(self::$called[__FUNCTION__]))
        {
            require SYSPATH . 'utf8' . DIRECTORY_SEPARATOR . __FUNCTION__ . EXT;

            // Function has been called
            self::$called[__FUNCTION__] = TRUE;
        }

        return _to_unicode($str);
    }

    /**
     * Takes an array of ints representing the Unicode characters and returns a UTF-8 string.
     * Astral planes are supported i.e. the ints in the input can be > 0xFFFF.
     * Occurrances of the BOM are ignored. Surrogates are not allowed.
     *
     *     $str = UTF8::to_unicode($array);
     *
     * The Original Code is Mozilla Communicator client code.
     * The Initial Developer of the Original Code is Netscape Communications Corporation.
     * Portions created by the Initial Developer are Copyright (C) 1998 the Initial Developer.
     * Ported to PHP by Henri Sivonen <hsivonen@iki.fi>, see http://hsivonen.iki.fi/php-utf8/
     * Slight modifications to fit with phputf8 library by Harry Fuecks <hfuecks@gmail.com>.
     *
     * @param   array    unicode code points representing a string
     * @return  string   utf8 string of characters
     * @return  boolean  FALSE if a code point cannot be found
     */
    public static function from_unicode($arr)
    {
        if (!isset(self::$called[__FUNCTION__]))
        {
            require SYSPATH . 'utf8' . DIRECTORY_SEPARATOR . __FUNCTION__ . EXT;

            // Function has been called
            self::$called[__FUNCTION__] = TRUE;
        }

        return _from_unicode($arr);
    }

}

// End UTF8

if (UTF8::$server_utf8 === NULL)
{
    // Determine if this server supports UTF-8 natively
    UTF8::$server_utf8 = extension_loaded('mbstring');
}
